﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Wiki.Entities;
using UMC.Web;

namespace UMC.Wiki.Activities
{
    class SubjectDynamicActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            var user = this.Context.Token.Identity();

            var sprojectId = this.AsyncDialog("Id", "auto");//);//.Value;


            var webr = UMC.Web.WebResource.Instance();

            var time = UMC.Data.Utility.UIntParse(this.AsyncDialog("Time", g =>
             {
                 var projectId = UMC.Data.Utility.UInt64Parse(sprojectId) ?? 0;
                 var search = new ProjectDynamic();
                 var form = request.SendValues ?? new UMC.Web.WebMeta();

                 int limit = UMC.Data.Utility.IntParse(form["limit"] as string, 25);
                 int start = UMC.Data.Utility.IntParse(form["start"] as string, 0);

                 string sort = form[("sort")] as string;
                 string dir = form[("dir")] as string;


                 var Keyword = (form["Keyword"] as string ?? String.Empty);

                 if (String.IsNullOrEmpty(Keyword) == false)
                 {
                     search.Title = Keyword;
                 }
                 if (projectId > 0)
                 {
                     search.project_id = projectId;
                 }
                 else
                 {
                     search.user_id = user.Id.Value;
                 }
                 var subs = new List<ProjectDynamic>();
                 var projectIds = new List<ulong>();
                 int nextIndex;
                 UMC.Data.Utility.Each(DataFactory.Instance().Search(search, start, out nextIndex, limit), dr =>
                   {
                       subs.Add(dr);
                       if (dr.project_id.HasValue && projectId == 0)
                       {
                           if (projectIds.Exists(r => r == dr.project_id.Value) == false)
                           {
                               projectIds.Add(dr.project_id.Value);
                           }
                       }

                   });
                 var projects = new List<Project>();
                 if (projectIds.Count > 0)
                 {
                     projects.AddRange(DataFactory.Instance().Projects(projectIds.ToArray()));
                 }

                 var ui2 = UISection.Create();
                 foreach (var sub in subs)
                 {

                     if (projectId > 0)
                     {
                         var data = new WebMeta().Put("alias", sub.Alias, "desc", sub.Explain).Put("time", UMC.Data.Utility.GetDate(UMC.Data.Utility.TimeSpan(sub.Time ?? 0)))
                             .Put("name", sub.Title)
                             .Put("src", webr.ImageResolve(request.Url, sub.user_id.Value, "1", 5));
                         data.Put("click", new UIClick(request.Model, "Dynamic", new WebMeta().Put("Id", sub.user_id).Put("Time", sub.Time)));
                         var cell = UICell.Create("IconNameDesc", data);

                         cell.Formats.Put("desc", "{alias} 在{time} {desc}");
                         cell.Style.Name("name").Size(14);
                         ui2.Add(cell);
                     }
                     else
                     {
                         var pro = projects.Find(d => d.Id == sub.project_id) ?? new Project();

                         var data = new WebMeta().Put("alias", pro.Caption, "desc", sub.Explain).Put("time", UMC.Data.Utility.GetDate(UMC.Data.Utility.TimeSpan(sub.Time ?? 0)))
                             .Put("name", sub.Title)
                             .Put("src", webr.ImageResolve(request.Url, sub.project_id.Value, "1", 5));
                         data.Put("click", new UIClick(request.Model, "Dynamic", new WebMeta().Put("Id", sub.user_id).Put("Time", sub.Time)));
                         var cell = UICell.Create("IconNameDesc", data);

                         cell.Formats.Put("desc", "{time} 在{alias}{desc}");
                         cell.Style.Name("name").Size(14);
                         ui2.Add(cell);
                     }
                 }
                 ui2.IsNext = nextIndex > 0;
                 if (start == 0 && subs.Count == 0)
                 {

                     ui2.Add("Desc", new UMC.Web.WebMeta().Put("desc", projectId > 0 ? "尚未有项目动态" : "尚未有个人动态").Put("icon", "\uF016")
                         , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                 }
                 else
                 {
                     ui2.StartIndex = nextIndex;
                 }

                 response.Redirect(ui2);
                 return this.DialogValue("none");
             }), 0);

            var dynamic = DataFactory.Instance().Dynamic(time, UMC.Data.Utility.Guid(sprojectId).Value);

            if (dynamic != null)
            {
                switch (dynamic.Type)
                {
                    case DynamicType.Member:
                        response.Redirect(request.Model, "Account", dynamic.user_id.ToString());
                        break;
                    case DynamicType.Project:
                        var pr = DataFactory.Instance().Project(dynamic.refer_id.Value);

                        if (pr != null)
                        {
                            response.Redirect(request.Model, "ProjectUI", dynamic.refer_id.ToString());
                        }
                        else
                        {
                            this.Prompt("动态关联已经错误");
                        }
                        break;
                    case DynamicType.Subject:
                        var pr3 = DataFactory.Instance().Subject(dynamic.refer_id.Value);

                        if (pr3 != null)
                        {

                            if (request.Url.Query.Contains("_v=Sub") && String.IsNullOrEmpty(pr3.Code) == false)
                            {
                                var sPro = DataFactory.Instance().Project(pr3.project_id.Value);

                                var iItem = DataFactory.Instance().ProjectItem(pr3.project_item_id.Value);

                                if (sPro != null && iItem != null)
                                {
                                    if (pr3.Status > -2)
                                    {
                                        if (pr3.Status < 1)
                                        {
                                            if (user.IsAuthenticated == false)
                                            {
                                                this.Prompt("此文档未发布，未有权限查看");
                                            }
                                            var member = DataFactory.Instance().ProjectMember(sPro.Id.Value, user.Id.Value);

                                            if (member != null)
                                            {
                                                switch (member.AuthType)
                                                {
                                                    case WebAuthType.Admin:
                                                    case WebAuthType.User:
                                                        break;
                                                    default:
                                                        this.Prompt("此文档未发布");
                                                        break;
                                                }

                                            }
                                            else
                                            {
                                                this.Prompt("此文档未发布");
                                            }

                                        }

                                        this.Context.Send("Subject.Path", new WebMeta().Put("Path", String.Format("{0}/{1}/{2}", sPro.Code, iItem.Code, pr3.Code)), true);
                                    }
                                    else
                                    {
                                        this.Prompt("此文档已经删除");
                                    }


                                }
                                else
                                {

                                    response.Redirect(request.Model, "UIData", dynamic.refer_id.ToString());
                                }
                            }
                            else
                            {
                                response.Redirect(request.Model, "UIData", dynamic.refer_id.ToString());
                            }

                        }
                        else
                        {
                            this.Prompt("此动态为信息动态");
                        }
                        break;
                    default:
                        this.Prompt("此动态为信息动态");
                        break;
                }
            }


        }

    }
}